﻿using LoveNote.Application.Share.Login;
using LoveNote.Database.Entities;
using LoveNote.Database.Helpers;
using LoveNote.Database.Interfaces;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using TookKit.Mvvm.Attributes;
using TookKit.Mvvm.Bindings;
using TookKit.Mvvm.Enums;
using LoveNote.Core.Helpers;
using LoveNote.Application.Picture.Views;
using System.IO;
using TookKit.Mvvm.Events;
using LoveNote.Application.Share.Message;
using System.Windows;
using System.Windows.Interop;

namespace LoveNote.Application.Picture.ViewModels
{
    [DependencyInjection(Lifetime.Singleton)]
    internal class PictureViewModel : ObservableObject
    {
        private List<PictureEntity> pictures;
        public List<PictureEntity> Pictures
        {
            get { return pictures; }
            set { SetProperty(ref pictures, value); }
        }

        private PictureEntity picture;
        public PictureEntity Picture
        {
            get { return picture; }
            set { SetProperty(ref picture, value); }
        }

        public ICommand LoadedCommand { get; }
        public ICommand AddPictureCommand { get; }
        public ICommand AddPictureFromClipboardCommand { get; }
        public ICommand DeletePictureCommand { get; }
        public ICommand PictureMouseUpCommand { get; }

        private IPictureRepository PictureRepository { get; }
        public ISession Session { get; }
        public PictureViewModel(ISession session, IPictureRepository pictureRepository)
        {
            Session = session;
            PictureRepository = pictureRepository;

            LoadedCommand = new RelayCommand(OnLoadedCommand);
            AddPictureCommand = new RelayCommand(OnAddPictureCommand);
            DeletePictureCommand = new RelayCommand<PictureEntity>(OnDeletePictureCommand);
            PictureMouseUpCommand = new RelayCommand<PictureEntity>(OnPictureMouseUpCommand);
            AddPictureFromClipboardCommand = new RelayCommand(OnAddPictureFromClipboardCommand);

            //从剪贴板中获取图像
            EventBus.Default.Subscribe<PasteMessage>((sender, message) =>
            {
                PasteImage();
            });
        }

        private void OnAddPictureFromClipboardCommand()
        {
            PasteImage();
        }

        private void PasteImage()
        {
            IDataObject dataObject = Clipboard.GetDataObject();            
            if (dataObject.GetDataPresent(DataFormats.Bitmap))
            {
                InteropBitmap interopBitmap = (InteropBitmap)dataObject.GetData(DataFormats.Bitmap);
                var memoryStream = new MemoryStream();
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(interopBitmap));
                encoder.Save(memoryStream);
                byte[] imageBytes = memoryStream.ToArray();
                string base64String = Convert.ToBase64String(imageBytes);
                string content = base64String;
                PictureEntity entity = new PictureEntity
                {
                    InsertDate = DateTime.Now,
                    Content = content,
                    UserId = Session.CurrentUser.Id,
                    Width = interopBitmap.PixelWidth,
                    Height = interopBitmap.PixelHeight,
                    Extension = ".png",
                };
                int count = PictureRepository.Insert(entity);
                if (count > 0)
                {
                    LoadPictures();
                }
            }
        }

        /// <summary>
        /// 浏览大图
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void OnPictureMouseUpCommand(PictureEntity entity)
        {
            var picture = entity.DeepClone();
            var view = new PreviewView();
            var viewmodel = TookKit.Mvvm.Container.Default.GetService<PreviewViewModel>();
            if (view != null && viewmodel!=null)
            {
                viewmodel.Picture = picture;
                view.DataContext = viewmodel;                
                view.ShowDialog();
            }
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="obj"></param>
        private void OnDeletePictureCommand(PictureEntity entity)
        {
            var result = Session.Show("是否执行当前操作？", System.Windows.MessageBoxButton.YesNo);
            if (result == null || result.Value == false)
                return;
            int count = PictureRepository.Delete(entity);
            if (count > 0)
            {
                LoadPictures();
            }
        }

        private void OnAddPictureCommand()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            //打开的文件选择对话框上的标题
            openFileDialog.Title = "请选择文件";
            //设置文件类型
            openFileDialog.Filter = "图片文件(*.jpg)|*.jpg|图片文件(*.png)|*.png|所有文件(*.*)|*.*";
            //设置默认文件类型显示顺序
            openFileDialog.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录
            openFileDialog.RestoreDirectory = true;
            //设置是否允许多选
            openFileDialog.Multiselect = false;
            //按下确定选择的按钮
            if (openFileDialog.ShowDialog().Value == true)
            {
                //获得文件路径
                string fileName = openFileDialog.FileName;
                string extension = Path.GetExtension(fileName);
                BitmapImage ImageSource = new BitmapImage(new Uri(fileName));
                string content = ImageHelper.GetImageString(fileName);
                PictureEntity entity = new PictureEntity
                {
                    InsertDate = DateTime.Now,
                    Content = content,
                    UserId = Session.CurrentUser.Id,
                    Width = ImageSource.PixelWidth,
                    Height = ImageSource.PixelHeight,
                    Extension = extension,
                };
                int count = PictureRepository.Insert(entity);
                if (count > 0)
                {
                    LoadPictures();
                }
            }
        }

        private void OnLoadedCommand()
        {
            
            LoadPictures();
        }

        private void LoadPictures()
        {
            Pictures = PictureRepository.GetAll()
                .FindAll(t => t.UserId == Session.CurrentUser.Id)
                .OrderByDescending(t => t.InsertDate)
                .ToList();
        }
    }
}
